<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue';
import { Global } from "../../Global";
import { HttpHelper } from "../../lib/HttpHelper";
import { AuthService } from '@/apis/admin/auth';

const servicePath = "/SystemPermission";
const isLoading = ref(<any>0);
const isBusy = ref(false);

const treeRef = ref<InstanceType<any>>();//如果Import ElTree，样式会丢失
const systemDatas = ref<any[]>();
const selectedSysId = ref<number>();

const menuDatas = ref<any[]>([]);
const treeProps = {
    children: 'Items',
    label: 'Caption',
}
var originalCheckedIds = <any[]>[];

onMounted(() => {
    bindSystems();
});

const bindSystems = async () => {
    isLoading.value++;
    try {
        menuDatas.value = await AuthService.GetMenus();
        console.log("菜单：", menuDatas.value.length);

        systemDatas.value = JSON.parse(await HttpHelper.get(`${servicePath}/GetAllSystems`, null));
    } catch (error) {
        Global.showError(error);
    }
    finally {
        isLoading.value--;
    }
}

const tabChange = async () => {
    isLoading.value++;
    try {
        originalCheckedIds = <any[]>JSON.parse(await HttpHelper.get(`${servicePath}/GetSystemPermissions`, { systemId: selectedSysId.value }));

        treeRef.value?.setCheckedKeys([]);
        originalCheckedIds.forEach(id => {
            treeRef.value?.setChecked(id, true, false);
        });
    } catch (error) {
        Global.showError(error);
    }
    finally {
        isLoading.value--;
    }
}

const saveClick = async () => {
    try {
        isBusy.value = true;
        var selectedItems = treeRef.value?.getCheckedNodes(false, true);

        //找出新增的操作
        var operations = <any[]>[];
        selectedItems?.forEach((item:any) => {
            if (originalCheckedIds.some(x => x == item.Id) == false) {
                operations.push({ Type: 2, MenuId: item.Id });
            }
        });


        //找出删除的操作
        originalCheckedIds.forEach(id => {
            if (selectedItems?.some((item:any) => item.Id == id) == false) {
                operations.push({ Type: 1, MenuId: id });
            }
        });

        console.log("操作结果：", operations);
        await HttpHelper.postJson(`${servicePath}/Excute`, { Operations: operations, SystemId: selectedSysId.value });
        originalCheckedIds = <any[]>JSON.parse(await HttpHelper.get(`${servicePath}/GetSystemPermissions`, { systemId: selectedSysId.value }));

        Global.showInfo("保存成功");
    } catch (error) {
        Global.showError(error);
    }
    finally {
        isBusy.value = false;
    }
}
</script>
<template>
    <div class="page-view-main">
        <div style="padding: var(--page-padding);flex:1;min-height:0px;display: flex;flex-direction: column;">
            <div class="page-view-panel">
                <el-empty description="没有定义任何子系统" v-if="systemDatas&&systemDatas.length==0"/>
                <el-container v-loading="isLoading" v-else>
                    <el-aside class="left">
                        <el-tabs tab-position="left" style="height: 100%" v-model="selectedSysId"
                            @tab-change="tabChange">
                            <el-tab-pane :label="sys.Name" v-for="sys in systemDatas" :key="sys.SystemId"
                                :name="sys.SystemId"></el-tab-pane>
                        </el-tabs>
                    </el-aside>
                    <el-main>
                        <el-container v-if="selectedSysId">
                            <el-header height="auto">
                                <div style="padding: 10px;text-align: right;">
                                    <el-button :loading="isBusy" type="primary" @click="saveClick">保存</el-button>
                                </div>
                            </el-header>
                            <el-main>
                                <el-scrollbar class="treearea">
                                    <el-tree ref="treeRef" :data="menuDatas" node-key="Id" :props="treeProps"
                                        show-checkbox />
                                </el-scrollbar>
                            </el-main>
                        </el-container>


                    </el-main>
                </el-container>
            </div>
        </div>
    </div>
</template>
<style scoped lang="scss">
.left {
    width: auto;
}

:deep(.el-tabs__content) {
    display: none;
}

:deep(.el-main) {
    padding: 0;
}
</style>